<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>One To Many - Foreign Key</title>
</head>
<body>
  <h3>One To Many - Foreign Key Association</h3>
  As previously seen in <em><q>Many to One -> Foreign Key</q></em> topic, the inverse side of a Many-to-One mapping is always a
  One-to-Many mapping in case of bi-directional relationship.
  <p>The JPA specification does not support unidirectional One-to-Many association where the <q>One</q> side is
  the owning  side due to the following reasons -
  <ul>
    <li>At object model level, a source entity (the <q>one</q> side in One-to-Many relationship) has collection of target entities
    (the <q>many</q> side in One-to-Many relationship). But at database level, there is no way to store unknown number of
    foreign key references in a single row representing the source entity. Therefore, the foreign key reference that points
    back to source entity, must be moved into target entity table.</li>
    <li>Furthermore, if the target entity table has foreign key reference to source entity table, not having corresponding mapping
    at object level for it doesn't make any sense and leaves the object model and database schema in <q>sort of</q> disconnected state.
    </li>
  </ul>
  </p>
  <p>
    Therefore, the bottomline is, if you are mapping a One-to-Many association using foreign key, you must make it bi-directional, with
    <q>many</q> side acting as the owning side. </p>
    <p>
    Getting down to the nuts and bolts, let's take an example of an employee and the department he works in. An employee can
    work in only one department while department can have many employees working in it. At object model level, Employee entity will
    maintain reference to Department entity while Department will maintain a collection of employees. The mapping is done by -
    <ol>
      <li>By annotating the Department reference in Employee with <em>@ManyToOne</em> annotation.</li>
      <li>By annotating the Employees collection in Department with <em>@OneToMany</em> annotation. the <em>mappedBy</em>
      attribute marks the department side as the inverse side and Employee as owning side.</li>
    </ol>
  </p>
</body>
</html>
